package com.dminvoicemanager.reports;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_Reports_Generator;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_RetailerCard_Report extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private String USER_SETTINGS = "usersettings";
	String currentReportName, selectFromDate, selectToDate;
	TextView txtHeadingReports;
	String currentUserTemp, currentUserPrefix, UserLocCode, PrintvlaueFI,
			PrintcurrentDisVal;
	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname;
	String TotalvlaueRecordRaw;
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", item_result_8 = "0";
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	String DefaultDate = "01-01-1900";
	Double TotalCasesLoading = 0.0, TotlPiecesLoading = 0.0,
			currentDisVal = 0.0;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "RID/RNAME");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_sales_summary_reportc);
		Bundle bundle = getIntent().getExtras();

		currentReportName = bundle.getString("REPORTNAME");
		selectFromDate = bundle.getString("FROMDATE");
		try {
			date = originalFormat.parse(selectFromDate.replaceAll("[-+/.^:,]",
					" "));
			Log.v(TAG, "Old Format :" + originalFormat.format(date));
			Log.v(TAG, "New Format :" + targetFormat.format(date));
			selectFromDate = targetFormat.format(date);
			LoadingFromDate = (Date) targetFormat.parse(selectFromDate);

		} catch (ParseException ex) {

		}
		selectToDate = bundle.getString("TODATE");
		try {
			date = originalFormat.parse(selectToDate.replaceAll("[-+/.^:,]",
					" "));
			Log.v(TAG, "Old Format :" + originalFormat.format(date));
			Log.v(TAG, "New Format :" + targetFormat.format(date));
			selectToDate = targetFormat.format(date);
			LoadingToDate = (Date) targetFormat.parse(selectToDate);

		} catch (ParseException ex) {

		}

		txtHeadingReports = (TextView) findViewById(R.id.txtHeadingReports);
		txtHeadingReports.setText(currentReportName);
		dmreportfromdate = (EditText) findViewById(R.id.dmreportfromdate);
		dmreportfromdate.setText(selectFromDate);
		dmreporttodate = (EditText) findViewById(R.id.dmreporttodate);
		dmreporttodate.setText(selectToDate);
		dmdisplayrepname = (EditText) findViewById(R.id.dmdisplayrepname);

		currentuserTemp();

		DisplayLoadingReport();
	}

	private void DisplayLoadingReport() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4", "item_result_5",
				"item_result_6" };

		int[] totrdes = new int[] { R.id.item_name, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {

			String query = "SELECT Itemcode,itemDescription,TxnType,DisAmt,sum(case when Type != 88 then CaseQty else 0 end),sum(case when Type != 88 then PiceQty else 0 end),sum(case when Type != 88 then Amt else 0 end),refInvitemCaseQty,SellPrice from FinvDet Where invsysdate >= '"
					+ selectFromDate.trim()
					+ "' AND invsysdate <= '"
					+ selectToDate.trim() + "'group by Itemcode";
			// String query =
			// "SELECT Itemcode,itemDescription,TxnType,DisAmt,CaseQty,PiceQty,Amt from FinvDet";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					// Item Name
					item_result_1 = allrowitemsdes.getString(1);
					// TxnType
					item_result_2 = allrowitemsdes.getString(2);
					// DisAmt
					item_result_3 = allrowitemsdes.getString(3);
					double DisAmtVal = Double.parseDouble(item_result_3);
					// CaseQty
					item_result_4 = allrowitemsdes.getString(4);
					// PiceQty
					item_result_5 = allrowitemsdes.getString(5);
					// Value
					item_result_6 = allrowitemsdes.getString(6);
					// Units With a Case
					item_result_7 = allrowitemsdes.getString(7);
					// Units Sell Price
					item_result_8 = allrowitemsdes.getString(8);

					if (item_result_2.equals("27") || DisAmtVal > 0) {
						double currentLoadingCases = 0.0, currentLoadingPieces = 0.0, currentUnitsCase = 0.0, currentCaseSellPrice = 0.0, freeIssueCaseVal = 0.0, freeIssuePiecesVal = 0.0, freeIssueVal = 0.0, totalValue = 0.0;

						currentLoadingCases = Double.parseDouble(item_result_4);
						TotalCasesLoading = TotalCasesLoading
								+ currentLoadingCases;

						currentLoadingPieces = Double
								.parseDouble(item_result_5);
						TotlPiecesLoading = TotlPiecesLoading
								+ currentLoadingPieces;
						// Units With a Case Value
						currentUnitsCase = Double.parseDouble(item_result_7);
						// Case Sell Price
						currentCaseSellPrice = Double
								.parseDouble(item_result_8);
						freeIssueCaseVal = currentCaseSellPrice
								* currentLoadingCases;
						freeIssuePiecesVal = (currentCaseSellPrice * currentLoadingPieces)
								/ currentUnitsCase;
						freeIssueVal = freeIssueCaseVal + freeIssuePiecesVal;
						String PrintfreeIssueVal = Double
								.toString(freeIssueVal);
						totalValue = freeIssueVal + DisAmtVal;
						String PrinttotalValue = Double.toString(totalValue);
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_1", item_result_1);
						maptrdes.put("item_result_2", PrintfreeIssueVal);
						maptrdes.put("item_result_3", item_result_3);
						maptrdes.put("item_result_4", item_result_4);
						maptrdes.put("item_result_5", item_result_5);
						maptrdes.put("item_result_6", PrinttotalValue);
						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_sales_summary_reportc_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);
					}
					// TotalCasesLoading =0.0,TotlPiecesLoading

					/*
					 * if(item_result_2.equals("27")){ String caseUnitPrice =
					 * allrowitemsdes.getString(6); String casePicesUnits =
					 * allrowitemsdes.getString(7); item_result_3 =
					 * allrowitemsdes.getString(3); double caseUnitPriceVal =
					 * Double.parseDouble(caseUnitPrice); double
					 * casePicesUnitsVal = Double.parseDouble(casePicesUnits);
					 * double caseTotValue = currentLoadingCases *
					 * caseUnitPriceVal; double pieceUnitPrice =
					 * (caseUnitPriceVal *casePicesUnitsVal) /
					 * casePicesUnitsVal;
					 * 
					 * if(item_result_3.length()!=0){ currentDisVal =
					 * Double.parseDouble(item_result_3); PrintcurrentDisVal =
					 * Double.toString(currentDisVal); } double vlaue =
					 * (caseTotValue + pieceUnitPrice) - currentDisVal;
					 * PrintvlaueFI = Double.toString(TotalCasesLoading);
					 * TotalvlaueRecordRaw = Double.toString(vlaue);
					 * 
					 * }
					 * 
					 * maptrdes.put("item_result_1", item_result_1); // print
					 * Case Qty sales 22 SA maptrdes.put("item_result_2",
					 * PrintvlaueFI); // print Pices Qty sales 22 SA
					 * maptrdes.put("item_result_3", PrintcurrentDisVal);
					 * 
					 * maptrdes.put("item_result_4", item_result_4);
					 * maptrdes.put("item_result_5", item_result_5);
					 * maptrdes.put("item_result_6", TotalvlaueRecordRaw); //
					 * fill in the grid_item layout fillMapstrdes.add(maptrdes);
					 * SimpleAdapter adaptertrdes = new SimpleAdapter(this,
					 * fillMapstrdes, R.layout.dm_sales_summary_reportc_raw,
					 * fromtrdes, totrdes); lvtypedes.setAdapter(adaptertrdes);
					 */
				}
				// -----Print Stock Loading Summary--------
				HashMap<String, String> maptrdesem = new HashMap<String, String>();
				maptrdesem.put("item_result_1", "");
				maptrdesem.put("item_result_2", "");
				maptrdesem.put("item_result_3", "");
				maptrdesem.put("item_result_4", "");
				maptrdesem.put("item_result_5", "");
				maptrdesem.put("item_result_6", "");
				/*
				 * // fill in the grid_item layout
				 * fillMapstrdes.add(maptrdesem); SimpleAdapter adaptertrdesem =
				 * new SimpleAdapter(this, fillMapstrdes,
				 * R.layout.dm_sales_summary_reportc_raw, fromtrdes, totrdes);
				 * lvtypedes.setAdapter(adaptertrdesem);
				 * 
				 * HashMap<String, String> maptrdessum = new HashMap<String,
				 * String>(); maptrdessum.put("item_result_1", ""); // print
				 * Case Qty sales 22 SA String TotalCasesLoadingStr = Double
				 * .toString(TotalCasesLoading);
				 * maptrdessum.put("item_result_2", ""); // print Pices Qty
				 * sales 22 SA String TotlPiecesLoadingStr = Double
				 * .toString(TotlPiecesLoading);
				 * maptrdessum.put("item_result_3", "");
				 * maptrdessum.put("item_result_4", TotalCasesLoadingStr);
				 * maptrdessum.put("item_result_5", TotlPiecesLoadingStr);
				 * maptrdessum.put("item_result_6", "200"); // fill in the
				 * grid_item layout fillMapstrdes.add(maptrdessum);
				 * SimpleAdapter adaptertrdessum = new SimpleAdapter(this,
				 * fillMapstrdes, R.layout.dm_sales_summary_reportc_raw,
				 * fromtrdes, totrdes); lvtypedes.setAdapter(adaptertrdessum);
				 */

			}
		}
		allrowitemsdes.close();
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					dmdisplayrepname.setText(currentUserTemp);
				}
			}
		}
		selectCurrentuserrec.close();
		mydb.close();
	}
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
